const orderModel = require('../models/orderModel');
const cartModel = require('../models/cartModel');
const { success, badRequest, notFound } = require('../utils/response');

const createOrder = async (req, res) => {
  try {
    const { address } = req.body;
    
    if (!address) {
      return badRequest(res, 'Address is required');
    }
    
    // 获取购物车内容
    const cartItems = await cartModel.getCartByUserId(req.userId);
    if (cartItems.length === 0) {
      return badRequest(res, 'Cart is empty');
    }
    
    // 计算总金额
    const totalAmount = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    
    // 创建订单
    const orderId = await orderModel.createOrder(
      req.userId,
      cartItems.map(item => ({
        product_id: item.product_id,
        quantity: item.quantity,
        price: item.price
      })),
      totalAmount,
      address
    );
    
    success(res, { orderId }, 'Order created successfully');
  } catch (err) {
    badRequest(res, 'Failed to create order');
  }
};

const getOrders = async (req, res) => {
  try {
    const orders = await orderModel.getOrdersByUserId(req.userId);
    success(res, orders);
  } catch (err) {
    notFound(res, 'Orders not found');
  }
};

const getOrder = async (req, res) => {
  try {
    const order = await orderModel.getOrderById(req.params.id, req.userId);
    if (!order) {
      return notFound(res, 'Order not found');
    }
    success(res, order);
  } catch (err) {
    notFound(res, 'Order not found');
  }
};

module.exports = {
  createOrder,
  getOrders,
  getOrder
};